<!-- 项目信息 -->
<template>
  <JYWPanel
    :key="'projectInfo'"
    p-k="projectInfo"
    title="项目信息"
    left-flag-title="创建人"
    :left-flag-value="panelInfo.createUser | member"
    right-flag-title="创建时间"
    :right-flag-value="panelInfo.createTime"
    :show-expand="$attrs.expand"
    :expand="expand"
    :height="$attrs.height"
    :disabled="disabled"
  >
    <el-form
      ref="form"
      :model="formData"
      label-width="140px"
      size="mini"
      label-position="right"
      :rules="rules"
      :disabled="disabled"
    >
      <el-form-item label="项目名称" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="项目描述" prop="memo">
        <el-input v-model="formData.memo" type="textarea" rows="5" />
      </el-form-item>
      <el-form-item label="项目起止日期" prop="time">
        <el-date-picker
          v-model="formData.time"
          class="w-100"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="关联项目">
        <ProjectSelect v-model="formData.upItem" :disabled="disabled" />
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="审核人" prop="reviewPeople">
            <UserSelect v-model="formData.reviewPeople" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目类型" prop="itemType">
            <DicSelect v-model="formData.itemType" dic-key="projectType" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="紧急程度" prop="urgentLevel">
            <DicSelect v-model="formData.urgentLevel" dic-key="itemLevel" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目负责人" prop="principalpeople">
            <UserSelect v-model="formData.principalpeople" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="项目参与人员">
            <UserSelect v-model="formData.itemUsers" multiple />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="项目级别">
            <el-radio-group v-model="formData.itemLevel">
              <el-radio
                v-for="item in dictionary['itemProjectLevel']"
                :key="item.id"
                :label="Number(item.value)"
              >
                {{ item.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col v-if="participants.length" :span="24">
          <el-form-item label="组员">
            <el-tag
              v-for="(v, i) in participants"
              :key="i"
              type="info"
              size="mini"
            >{{ v }}</el-tag>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="附件">
        <Upload v-model="formData.file" />
      </el-form-item>
    </el-form>
    <template v-if="itemCode">
      <el-row
        style="
          display: flex;
          align: center;
          padding: 25px 0 9px 0;
          border-top: 1px solid #ecf0f7;
        "
      >
        <el-col :span="24">
          <span style="margin-right: 20px">任务信息</span>
          <pure-button
            :label="!isLookTask ? '编辑任务' : '查看任务'"
            @click="clickEditTaskBtn"
          />
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-table
            ref="infoTable"
            :data="taskTreeList"
            style="width: 100%; margin-bottom: 20px"
            row-key="id"
            border
            default-expand-all
            :tree-props="{ children: 'children' }"
            size="mini"
            :indent="0"
            append-to-body
            :cell-style="tableStyle.cellStyle"
            :default-sort="{ prop: 'indexNum', order: 'ascending' }"
            @select="selectCloumn"
          >
            <el-table-column
              v-for="v in tableConfig"
              :key="v.id"
              :show-overflow-tooltip="v.slot ? false : true"
              :prop="v.property ? v.property : null"
              :label="v.label ? v.label : null"
              align="left"
              :width="v.w ? v.w : null"
              :formatter="v.formatter ? v.formatter : null"
              :selectable="v.disabled ? v.disabled : null"
            />
          </el-table>
        </el-col>
      </el-row>
    </template>
  </JYWPanel>
</template>

<script>
import { mixins_base, mixins_rules, mixins_task, } from '@/minxins/project';
import { mapGetters, mapMutations, mapState, } from 'vuex';
import { date, member, } from '@/filters';
import _ from 'lodash';
import vm from '@/main';
import ProjectAPI from '@/apis/project';
import tableStyle from '../../style/table';
import moment from 'moment';
import ProjectSelect from '../select/selectProject.vue';
import Text from '@/views/project/components/text/text.vue';
import drawerWidth from '@/views/project/common/width/drawer';
export default {
  name: 'ProjectInfo',
  components: {
    Upload: () => import('@/components/upload'),
    // eslint-disable-next-line vue/no-unused-components
    TaskTable: () => import('../../setUp/components/taskTable.vue'),
    ProjectSelect,
    DicSelect: () => import('../select/selectDic'),
  },
  mixins: [mixins_base, mixins_rules, mixins_task],
  data() {
    return {
      tableStyle,
      visibles: {
        referVisible: false,
        saveVisible: false,
        addVisible: false,
      },
      id: 0,
      // 上级项目id 用作提示处理
      upItemId: null,
      formData: {
        name: '',
        memo: '',
        time: [],
        upItem: '',
        reviewPeople: '',
        itemType: '',
        urgentLevel: '',
        principalpeople: '',
        itemUsers: [],
        itemLevel: '',
        file: JSON.stringify([]),
      },

      panelInfo: {
        createUser: '',
        createTime: '',
      },
      tableCheckedParams: {
        allChecked: false,
        childCheckeds: [],
      },
      SW: {
        keyWord: '',
        W: {
          code: '',
        },
        N: 999,
        P: 1,
      },
      rules: {
        name: [
          {
            required: true,
            trigger: 'blur',
            message: '请输入项目名称',
          }
        ],
        memo: [
          {
            required: true,
            trigger: 'blur',
            message: '请输入项目描述',
          }
        ],
        time: [
          {
            required: true,
            trigger: 'array',
            message: '请选择项目起止日期',
          }
        ],
        reviewPeople: [
          {
            required: true,
            trigger: 'change',
            message: '请选择审核人',
          }
        ],
        itemType: [
          {
            required: true,
            trigger: 'blur',
            message: '请选择项目类型',
          }
        ],
        urgentLevel: [
          {
            required: true,
            trigger: 'blur',
            message: '请选择紧急程度',
          }
        ],
        principalpeople: [
          {
            required: true,
            trigger: 'change',
            message: '请选择项目负责人',
          }
        ],
      },
    };
  },
  computed: {
    tableConfig() {
      return [
        {
          label: '序号',
          property: 'indexNum',
          w: 'auto',
          formatter: (v) => {
            return vm.$createElement('span', {
              style: {
                color: v['approvalStatus'] === 2 ? '#67C23A' : '#F56C6C',
              },
              domProps: {
                innerHTML: v.indexNum,
              },
            });
          },
        },
        {
          label: '任务名称',
          property: 'name',
          w: '160px',
          formatter: (v) => {
            return this.$createElement(Text, { props: { textContent: v['name'], }, });
          },
        },
        {
          label: '预计工时',
          property: 'planUse',
          w: '100px',
          formatter: (v) => {
            return v['planUse'] ? v['planUse'] + '天' : '';
          },
        },
        {
          label: '负责人',
          property: 'principal',
          w: '100px',
          formatter: (v) => {
            return member(v['principal']);
          },
        },
        {
          label: '开始/截止日期',
          property: 'startTime',
          w: '140px',
          formatter: (v) => {
            if (!v['startTime'] && !v['endTime']) {
              const val = this.computedMileageSE(v['id'], this.taskList);
              return this.$createElement('div', {}, [
                this.$createElement('p', val[0]),
                this.$createElement('p', val[1])
              ]);
            }
            return this.$createElement('div', {}, [
              this.$createElement('p', moment(v['startTime']).format('YYYY-MM-DD HH:mm')),
              this.$createElement('p', moment(v['endTime']).format('YYYY-MM-DD HH:mm'))
            ]);
          },
        }
      ];
    },
    ...mapGetters(['userInfo']),
    ...mapState('project/index', {
      expand: (v) => {
        return v['pancelExpandOptions'].projectInfo;
      },
      disabled: (v) => {
        return v['pancelDisabledOptions'].projectInfo;
      },
    }),
  },
  mounted() {
    this.$nextTick(() => {
      if (this.itemCode) {
        this.getEditValue();
      } else {
        this.panelInfo = {
          createUser: this.userInfo.id,
          createTime: moment().format('YYYY-MM-DD HH:mm'),
        };
      }
    });
    this.SW.W.code = 'all';
  },
  methods: {
    ...mapMutations('project/index', ['SET_ITEM_CODE']),
    computedMileageSE(id, childList) {
      const theIdList = childList.filter(e => e.parentId === id);
      if (theIdList.length) {
        const timeStartTimeGather = theIdList.map(e => new Date(e.startTime).getTime());
        const timeEndTimeGather = theIdList.map(e => new Date(e.endTime).getTime());
        const minTime = moment(_.min(timeStartTimeGather)).format('YYYY-MM-DD HH:mm');
        const maxTime = moment(_.max(timeEndTimeGather)).format('YYYY-MM-DD HH:mm');
        return [minTime, maxTime];
      }
      return ['-', '-'];
    },
    onDone(data) {
      this.afterDone(this.refName);
      this[this.ArgumentName] = data;
    },
    async getEditValue() {
      const rs = this.getterPanelGroupData;
      const info = rs.info;
      this.formData.name = info.title;
      this.formData.memo = info.remark;
      this.formData.time = [
        info.startTime || Date.now(),
        info.endTime || Date.now()
      ];
      this.formData.reviewPeople = info.reviewer;
      this.formData.itemType = info.itemType;
      this.formData.urgentLevel = info.priority;
      this.formData.principalpeople = info.principal;
      this.formData.itemUsers = info.joinUser;
      this.formData.itemLevel = info.projectLevel;
      this.formData.file = info.enclosure;
      this.formData.joinUser = info.joinUser;
      this.formData.upItem = info.parentId;
      this.upItemId = info.parentId || null;
      for (const i in this.formData) {
        if (!this.formData[i]) {
          this.formData[i] = '';
        }
      }
      this.panelInfo = _.pick(info, Object.keys(this.panelInfo));

      this.SET_TASK_LIST(rs.work);
    },
    async successTask() {
      if (this.itemCode) {
        this.SET_TASK_LIST(
          await ProjectAPI.setUp.getTaskList({ itemCode: this.itemCode, })
        );
      }
    },

    async submit(type) {
      return new Promise((r, j) => {
        let submitParams = {};
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            if (!this.taskTreeList.length && type === 'confirm' && this.itemCode) {
              j('请先完善任务信息');
              return;
            }
            if (!this.taskTreeList.length && type === 'confirm' && !this.itemCode) {
              j('请先保存');
              return;
            }

            submitParams = {
              // itemCode: this.itemCode || '',
              parentId: this.formData.upItem,
              reviewer: this.formData.reviewPeople,
              title: this.formData.name,
              remark: this.formData.memo,
              enclosure: this.formData.file,
              startTime: date(this.formData.time[0], 'YYYY-MM-DD'),
              endTime: date(this.formData.time[1], 'YYYY-MM-DD'),
              itemType: this.formData.itemType,
              principal: this.formData.principalpeople,
              priority: this.formData.urgentLevel,
              projectLevel: this.formData.itemLevel,
              joinUser: this.formData.itemUsers,
            };
            if (this.itemCode) {
              submitParams['itemCode'] = this.itemCode;
            } else {
              this.upItemId = submitParams.parentId || null;
            }
            try {
              let code = this.itemCode || '';
              // 上级项目存在，并且上级项目被清空
              if (this.upItemId && !submitParams.parentId) {
                this.$confirm(
                  '上级项目已被清空,是否继续操作?此操作会清空任务!',
                  '提示',
                  {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                  }
                )
                  .then(async () => {
                    code = await ProjectAPI.setUp.createOrSaveSetup(
                      submitParams,
                      type
                    );
                    r({
                      itemCode: this.itemCode,
                    });
                    this.SET_ITEM_CODE(code);
                    this.successTask();
                  })
                  .catch(() => {});
                // 原有的上级项目 与 现有的上级项目不一样
              } else if (
                this.upItemId &&
                this.upItemId !== submitParams.parentId
              ) {
                this.$confirm(
                  '上级项目已改变,是否继续操作?此操作会覆盖原有的任务!',
                  '提示',
                  {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                  }
                )
                  .then(async () => {
                    code = await ProjectAPI.setUp.createOrSaveSetup(
                      submitParams,
                      type
                    );
                    r({
                      itemCode: this.itemCode,
                    });
                    this.SET_ITEM_CODE(code);
                    this.successTask();
                  })
                  .catch(() => {});
              } else {
                code = await ProjectAPI.setUp.createOrSaveSetup(
                  submitParams,
                  type
                );

                r({
                  itemCode: this.itemCode,
                });
                this.SET_ITEM_CODE(code);
                this.successTask();
              }
            } catch (error) {
              j(error);
            }
          } else {
            j('表单校验未通过');
          }
        });
      });
    },
    clickEditTaskBtn() {
      this.$innerDrawer({
        width: drawerWidth.larger_pr,
        component: () => (
          <TaskTable onDone={this.done} time={this.formData.time} />
        ),
      });
    },
    done() {},

    // ------------- 表格 复选框 选中处理 暂时放弃 后期针对任务列表的处理
    selectAll(checked) {},
    selectCloumn(checked, row) {
      // this.SET_TASK_ID(s.map(e => e.id));
      // this.FETCH_TASK_LIST_DISABLED({ checked, row, });
    },
  },
};
</script>
<style lang='scss' scoped>
.w-100 {
  width: 100%;
}
.content-span {
  font-size: 14px;
  color: #879bba;
  > p {
    font-size: 14px;
    font-weight: 400;
    text-align: justify;
    color: #dcdfe6;
    margin: 0;
    padding: 0;
  }
}
.el-tag + .el-tag {
  margin-left: 4px;
}
</style>
